# Methods added to this helper will be available to all templates in the application.
require 'string'
module ApplicationHelper
  #Return a link for use in layout navigation.
  def nav_link(text,controller,action="index")
    link_to_unless_current text, :controller => controller, :action => action, :id => nil
  end
  
  def logged_in?
    not session[:user_id].nil?
  end

  def error_div(model, field, field_name)
    return "" unless model
    field = field.is_a?(Symbol) ? field.to_s : field
    errors = model.errors[field]
    str = ""
    if errors
     str = %Q(<div class="errors">#{errors.is_a?(Array) ? errors.map{|e| field_name + e}.join(",") : field_name << errors}</div>)
    end
    str
  end
  
  def text_area_for(f,method,model,options={})
    field_for(f,method,model,"area",options)
  end
  
  def text_field_for(f,method,model,options={})
    field_for(f,method,model,"field",options)
  end
  
  def pass_field_for(f,method,model,options={})
    field_for(f,method,model,"pass",options)
  end
  
  def file_field_for(f,method,model,options={})
    field_for(f,method,model,"file",options)
  end
  
  def field_for(f,method,model,type,options)
    required = options.delete(:required)
    text = options.delete(:text)
    case type
      when "field"
        str = f.text_field( method, options )
      when "area"
        str = f.text_area( method, options )
      when "pass"
        str = f.password_field( method, options )
      when "file"
        str = f.file_field(method,options)
      else
        ""
    end
    label_text = label_for( method, required, text) 
    error = error_div(model,method,text)
    str = str+error.html_safe
    wrap_field( label_text + str, required )  
  end
  
  def wrap_field(text,required)
    field_class = "field"
    if required
      field_class = "required"
    end
    "<div class='#{field_class}'>" + text + "</div>"
  end
  
  def label_for(method,required,text)
    extra=""
    if required
      extra = "<span class='required_mark'>*</span>"
    end
   "<div class='form_text'>"+"<label for='"+method.to_s+"' class='label'>"+text+"</label>"+extra+"</div>"
  end

  def simple_text_field_for(f,method,options={})
    text = options.delete(:text)
    required = options.delete(:required)
    label = label_for(method,required,text)
    form_field = f.text_field(method,options)
    content_tag( "div", "#{label}#{form_field}", :class => "form_row" )
  end
  
  def simple_text_area_for(f,method,options={})
    text = options.delete(:text)
    required = options.delete(:required)
    label = label_for(method,required,text)
    form_field = f.text_area(method,options)
    content_tag( "div", "#{label}#{form_field}", :class => "form_row" )
  end

  
end
